<?php
namespace Tbf\Bundle\SerializerBundle\Register;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * 某种序列化注册器
 * 不做缓存,
 */
class SingleRegister {
    protected $container;
    protected $handler_service_id_list=array();
    protected $handler_list = array();
    function __construct(ContainerInterface $container){
        $this->container = $container;
    }
    function register($class_name,$handler){
        $this->handler_list[$class_name] = $handler;
    }
    function registerByMapClassNameServiceId($map){
        foreach($map as $class_name=>$service_id){
            $this->handler_service_id_list[$class_name] = $service_id;
            $this->handler_list[$class_name] = 'service_id';
        }
    }

    /**
     * 根据类型返回对象
     * @param $class_name
     * @return null|object
     */
    function getByClassName($class_name){
        $handler = $this->getHandlerSimple($class_name);
        if ($handler!==null) {
            return $handler;
        }
        $origin_class_name = $class_name;
        while (true) {
            $class_name = get_parent_class($class_name);
            if ($class_name===false) {
                return null;
            }
            $handler = $this->getHandlerSimple($class_name);
            if ($handler!==null) {
                $this->handler_list[$origin_class_name] = $handler;
                return $handler;
            }
        }
        return null;
    }
    protected function getHandlerSimple($class_name)
    {
        if (empty($this->handler_list[$class_name])) {
            return null;
        }
        $handler = $this->handler_list[$class_name];
        if ($handler!=='service_id') {
            return $handler;
        }
        $handler = $this->container->get($this->handler_service_id_list[$class_name]);
        $this->handler_list[$class_name] = $handler;

        return $handler;
    }
}